#include "Thread.hpp"
#include "lockGuard.hpp"
using namespace std;

pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;

void run1(void *args)
{
    std::string message = static_cast<const char *>(args);
    int cnt = 10;
    while (cnt)
    {
        LockGuard lock(&mutex);//但构建临时对象时，先调用LockGuard构造函数，自动加锁
        //当整个代码块结束的时候，会自动释放临时对象lock，也就自动调用LockGuard析构函数，自动解锁
        //这种叫做RAII风格的锁
        cout << "我是一个线程, " << message << ", cnt: " << cnt-- << endl;
        sleep(1);
    }
}

int main()
{
    Thread t1(1, run1, (void *)"this is thread 1");
    Thread t2(2, run1, (void *)"this is thread 2");
    cout << "thread name:" << t1.threadname() << "\tthread id:" << t1.threadid() << "\tthread status:" << t1.status() << endl;
    cout << "thread name:" << t2.threadname() << "\tthread id:" << t2.threadid() << "\tthread status:" << t2.status() << endl;

    t1.run();
    t2.run();
    cout << "thread name:" << t1.threadname() << "\tthread id:" << t1.threadid() << "\tthread status:" << t1.status() << endl;
    cout << "thread name:" << t2.threadname() << "\tthread id:" << t2.threadid() << "\tthread status:" << t2.status() << endl;

    t1.join();
    t2.join();
    cout << "thread name:" << t1.threadname() << "\tthread id:" << t1.threadid() << "\tthread status:" << t1.status() << endl;
    cout << "thread name:" << t2.threadname() << "\tthread id:" << t2.threadid() << "\tthread status:" << t2.status() << endl;

    return 0;
}